# $Id: whois.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

import optparse

from django.conf import settings
from djanet.lib import exception, ip, stdlib, log
from djanet.tools.lib import getopts
from djanet.utils import runonce, tree, whois

class Command(getopts.GetOptions):
   option_list = (
         optparse.make_option("-s", "--server", action = "store",
            help = "server [ ARIN, LACNIC, RIPE, APNIC, AFRINIC, RADB ] default = None", default = "none", type = "choice", choices = whois.GetServers(),
            dest = "server"),
         ) + getopts.GetOptions.option_list

   help = "Whois inforation"

   def __init__(self):
      super(Command, self).__init__()
      self.prog = __file__.split("/")[-1]
      self._defServer = "whois.arin.net"
      runonce.build_tree()

   def whois_asn(self, ASNumber, Server):
      retval = None
      if ASNumber and len(tree.ASNList):
         entry = None
         for node in tree.ASNList:
            if ASNumber in node:
               entry = node
               break

         print entry, entry[ASNumber]
         client = None
         try:
            if Server:
               client = whois.Whois(Server)
            else:
               if entry:
                  client = whois.Whois(entry[ASNumber])
               else:
                  client = whois.Whois(self._defServer)
         except exception.WhoisError, message:
            print message
         else:
            query = None
            if Server:
               query = "as%s\r\n" %str(ASNumber)
            else:
               if entry:
                  query = "%s%s\r\n" %(entry.query, str(ASNumber))
               else:
                  query = "as%s\r\n" %str(ASNumber)

            if query:
               retval = client.info(query)
         finally:
            if client:
               client.Close()

      if retval:
         print retval

      
   def handle(self, *args, **options):
      opttype = None
      option = None
      try:
         (opttype, option) = args[0:2]
      except IndexError, message:
         self.error(
               "need asnumber (ex: 'as 3356') or ipaddress (ex: 'n 4.2.2.2')")

      if opttype and option:
         server = options.get("server")
         if server == "none":
            server = None

         print option, opttype
         if opttype == "as":
            self.whois_asn(option, server)
         elif opttype == "n":
            self.whois_ipv4(option, server)

